//
//  BaseNavigationViewController.m
//  EveryDay
//
//  Created by lizq on 15/8/14.
//  Copyright (c) 2015年 lizq. All rights reserved.
//
#define WEAKSELF __weak typeof(self)weakSelf = self;
#define KEY_WINDOW  [[UIApplication sharedApplication] keyWindow]
#define TOP_VIEW    [[UIApplication sharedApplication] keyWindow].rootViewController.view
#define VIEW_WIDTH  [UIScreen mainScreen].bounds.size.width
#define kAnimationDuration 0.5

#import "BaseNavigationViewController.h"
#import "BaseViewController.h"
@interface BaseNavigationViewController ()

@end

@implementation BaseNavigationViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.screenShotsList = [[NSMutableArray alloc]initWithCapacity:2];
        self.canDragBack = YES;
    }
    return self;
}

- (void)viewDidDisappear:(BOOL)animated{
    self.screenShotsList = nil;
    
    [self.backgroundView removeFromSuperview];
    self.backgroundView = nil;
    [super viewDidDisappear:animated];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self
                                                                                action:@selector(paningGestureReceive:)];
    recognizer.delegate = self;
    [recognizer delaysTouchesBegan];
    [self.view addGestureRecognizer:recognizer];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:(BOOL)animated];
    
    if (self.screenShotsList.count == 0)
    {
        UIImage *capturedImage = [self capture:TOP_VIEW];
        if (capturedImage) {
            [self.screenShotsList addObject:capturedImage];
        }
    }
}

// override the push method
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    UIImage *capturedImage = [self capture:TOP_VIEW];
    if (capturedImage) {
        [self.screenShotsList addObject:capturedImage];
    }
    [super pushViewController:viewController animated:animated];
}

// override the pop method
- (UIViewController *)popViewControllerAnimated:(BOOL)animated
{
    [self.screenShotsList removeLastObject];
    return [super popViewControllerAnimated:animated];
}

#pragma mark - Utility Methods -

// get the current view screen shot
- (UIImage *)capture:(UIView *)view
{
    //截屏
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

// set lastScreenShotView 's position and alpha when paning
- (void)moveViewWithX:(float)x
{
    //    NSLog(@"Move to:%f",x);
    x = x > VIEW_WIDTH?VIEW_WIDTH:x;
    x = x < 0?0:x;
    CGRect frame = TOP_VIEW.frame;
    frame.origin.x = x;
    TOP_VIEW.frame = frame;
    float scale = (x/(VIEW_WIDTH*10))+0.9;
    float alpha = 0.4 - (x/800);
    self.lastScreenShotView.transform = CGAffineTransformMakeScale(scale, scale);
    self.blackMask.alpha = alpha;
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    
    CGPoint point = [touch locationInView:self.view];
    if(point.x > 50)
    {
        return NO;
    }
    if ([touch.view isKindOfClass:[UIButton class]])
    {
        return NO;
    }
    if (self.viewControllers.count <= 1 || !self.canDragBack)
    {
        return NO;
    }
    return YES;
}

#pragma mark - Gesture Recognizer -

- (void)paningGestureReceive:(UIPanGestureRecognizer *)recoginzer
{
    // If the viewControllers has only one vc or disable the interaction, then return.
    if (self.viewControllers.count <= 1 || !self.canDragBack) return;
    
    // we get the touch position by the window's coordinate
    CGPoint touchPoint = [recoginzer locationInView:KEY_WINDOW];
    
    // begin paning, show the backgroundView(last screenshot),if not exist, create it.
    if (recoginzer.state == UIGestureRecognizerStateBegan) {
        
        self.startTouch = touchPoint;
        if(self.startTouch.x > VIEW_WIDTH / 6.0)
        {
            return; //边角响应滑动返回
        }
        _isMoving = YES;
        
        if (self.backgroundView == nil)
        {
            CGRect frame = TOP_VIEW.frame;
            self.backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width , frame.size.height)];
            [self.backgroundView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]];
            [TOP_VIEW.superview insertSubview:self.backgroundView belowSubview:TOP_VIEW];
            self.blackMask = [[UIView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width , frame.size.height)];
            self.blackMask.backgroundColor = [UIColor blackColor];
            [self.backgroundView addSubview:self.blackMask];
        }
        self.backgroundView.hidden = NO;
        if (self.lastScreenShotView != nil){
            [self.lastScreenShotView removeFromSuperview];
        }
        UIImage *lastScreenShot = [self.screenShotsList lastObject];
        self.lastScreenShotView = [[UIImageView alloc]initWithImage:lastScreenShot];
        [self.backgroundView insertSubview:self.lastScreenShotView belowSubview:self.blackMask];
        
    }else if (recoginzer.state == UIGestureRecognizerStateEnded){
        
        if(self.startTouch.x >  VIEW_WIDTH / 6.0)
        {
            return; //边角响应滑动返回
        }
        if (touchPoint.x - self.startTouch.x > 50)
        {
            [UIView animateWithDuration:0.3 animations:^{
                [self moveViewWithX:VIEW_WIDTH];
            } completion:^(BOOL finished) {
                
                [self popViewControllerAnimated:NO];
                CGRect frame = TOP_VIEW.frame;
                frame.origin.x = 0;
                TOP_VIEW.frame = frame;
                _isMoving = NO;
                self.backgroundView.hidden = YES;
            }];
        }
        else
        {
            [UIView animateWithDuration:0.3 animations:^{
                [self moveViewWithX:0];
            } completion:^(BOOL finished) {
                _isMoving = NO;
                self.backgroundView.hidden = YES;
            }];
        }
        return;
        
        // cancal panning, alway move to left side automatically
    }else if (recoginzer.state == UIGestureRecognizerStateCancelled){
        
        [UIView animateWithDuration:0.3 animations:^{
            [self moveViewWithX:0];
        } completion:^(BOOL finished) {
            _isMoving = NO;
            self.backgroundView.hidden = YES;
        }];
        
        return;
    }
    // it keeps move with touch
    if (_isMoving) {
        [self moveViewWithX:touchPoint.x - self.startTouch.x];
    }
}

//页面跳转
- (void)pushViewController:(UIViewController *)viewController bAnimation:(BOOL)animation {
    if([viewController isKindOfClass:[BaseViewController class]]) {
        //frame动画
        WEAKSELF
        BaseViewController *vc = (BaseViewController *)viewController;
        UIImage *to = [self capture:vc.view];
        self.toView = [[UIImageView alloc] initWithFrame:[vc beginFrame]];
        [self.toView setImage:to];
        [self.view addSubview:self.toView];
        CGRect endFrame = [vc endFrame];
        [UIView animateWithDuration:kAnimationDuration animations:^{
            [weakSelf.toView setFrame:endFrame];
        } completion:^(BOOL finished) {
            [weakSelf pushViewController:vc animated:NO];
            [self.toView removeFromSuperview];
        }];
    }else {
        [self pushViewController:viewController animated:animation];
    }
}

- (void)popToViewController:(UIViewController *)viewController bAnimation:(BOOL)animation {
    if([viewController isKindOfClass:[BaseViewController class]]) {
        //frame动画
        WEAKSELF
        BaseViewController *vc = (BaseViewController *)viewController;
        UIImage *to = [self capture:vc.view];
        self.toView = [[UIImageView alloc] initWithFrame:[vc beginFrame]];
        [self.toView setImage:to];
        [self.view addSubview:self.toView];
        CGRect endFrame = [vc endFrame];
        [UIView animateWithDuration:kAnimationDuration animations:^{
            [weakSelf.toView setFrame:endFrame];
        } completion:^(BOOL finished) {
            [weakSelf popToRootViewControllerAnimated:NO];
            [self.toView removeFromSuperview];
        }];
    }else {
        [self popToRootViewControllerAnimated:animation];
    }
}

- (void)popToRootViewControllerWithViewController:(UIViewController *)viewController bAnimation:(BOOL)animation {
    if([viewController isKindOfClass:[BaseViewController class]]) {
        WEAKSELF
        BaseViewController *vc = (BaseViewController *)viewController;
        CGRect beginFrame = [vc beginFrame];
        CGRect endFrame = [vc endFrame];
        [self popToRootViewControllerAnimated:NO];
        
        UIImage *to = [self capture:vc.view];
        self.toView = [[UIImageView alloc] initWithFrame:endFrame];
        [self.toView setImage:to];
        [self.view addSubview:self.toView];
        
        [UIView animateWithDuration:kAnimationDuration animations:^{
            [weakSelf.toView setFrame:beginFrame];
        } completion:^(BOOL finished) {
            [self.toView removeFromSuperview];
        }];
    }else {
        [self popToRootViewControllerAnimated:animation];
    }
}

- (void)popViewController:(UIViewController *)viewController bAnimaiton:(BOOL)animation {
    if([viewController isKindOfClass:[BaseViewController class]]) {
        WEAKSELF
        BaseViewController *vc = (BaseViewController *)viewController;
        CGRect beginFrame = [vc beginFrame];
        CGRect endFrame = [vc endFrame];
        [self popViewControllerAnimated:NO];
        
        UIImage *to = [self capture:vc.view];
        self.toView = [[UIImageView alloc] initWithFrame:endFrame];
        [self.toView setImage:to];
        [self.view addSubview:self.toView];
        
        [UIView animateWithDuration:kAnimationDuration animations:^{
            [weakSelf.toView setFrame:beginFrame];
        } completion:^(BOOL finished) {
            [self.toView removeFromSuperview];
        }];
    }else {
        [self popViewControllerAnimated:animation];
    }
}


@end
